package org.ycx.upms.web.controller;

import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.ycx.common.constants.RespCode;
import org.ycx.common.dto.RespMSG;
import org.ycx.common.validator.EmailValidator;
import org.ycx.common.validator.NotNullValidator;
import org.ycx.common.validator.ValidationErrorToString;
import org.ycx.upms.common.constants.SecurityConstants;
import org.ycx.upms.dao.enmus.BaseState;
import org.ycx.upms.dao.model.*;
import org.ycx.upms.service.ISecGroupService;
import org.ycx.upms.service.ISecRoleService;
import org.ycx.upms.service.ISecUserService;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * SecUsercontroller
 * Created by yang on 2017-07-19 16:25:40.
 */
@Controller
@RequestMapping("/sec/user")
public class SecUserController {

    private static Logger _log = LoggerFactory.getLogger (SecUserController.class);

    private static final String PRE = "sec/user/";

    @Autowired
    private ISecUserService service;

    @Autowired
    private ISecRoleService roleService;

    @Autowired
    private ISecGroupService groupService;

    /**
     * 首页
     *
     * @param modelMap
     * @return
     */
    @RequestMapping("/index.html")
    public String indexPage(ModelMap modelMap) {
        return PRE + "index";
    }

    /**
     * 新增页面
     *
     * @param modelMap
     * @return
     */
    @RequestMapping("/create.html")
    public String createPage(ModelMap modelMap) {
        return PRE + "create";
    }

    /**
     * 更新页面
     *
     * @param id
     * @param modelMap
     * @return
     */
    @RequestMapping("/update/{id}.html")
    public String updatePage(@PathVariable("id") int id, ModelMap modelMap) {
        SecUser bean = this.service.selectByPrimaryKey (id);
        modelMap.put ("bean", bean);
        return PRE + "update";
    }

    /**
     * 更新页面
     *
     * @param id
     * @param modelMap
     * @return
     */
    @RequestMapping("/detail/{id}.html")
    public String detailPage(@PathVariable("id") int id, ModelMap modelMap) {
        SecUser bean = this.service.selectByPrimaryKey (id);
        modelMap.put ("bean", bean);
        return PRE + "detail";
    }

    @RequestMapping("/role.html")
    public String rolesPage(Integer uid, ModelMap ui) {
        SecRoleExample sre = new SecRoleExample ();
        sre.createCriteria ().andRoleStateEqualTo (BaseState.MALE.getKey () + "");
        List<SecRole> roles = roleService.selectByExample (sre);
        List<Integer> rids = this.service.selectRidsByUser (uid);
        SecUser user = this.service.selectByPrimaryKey (uid);
        ui.put ("roles", roles);
        ui.put ("rids", rids);
        ui.put ("user", user);
        return PRE + "roles";
    }

    @RequestMapping("/role")
    @ResponseBody
    public RespMSG grantRole(Integer uid, Integer rids[]) {
        int res = 0;
        res = this.service.updateUserRole (uid, rids);
        RespMSG msg = new RespMSG (RespCode.SUCCESS);
        msg.setData (res);
        return msg;
    }

    @RequestMapping("/group.html")
    public String groupsPage(Integer uid, ModelMap ui) {
        SecGroupUserExample sgu = new SecGroupUserExample ();
        sgu.createCriteria ().andUidEqualTo (uid);
        List<SecGroup> groups = this.groupService.selectByExample (new SecGroupExample ());
        List<Integer> gids = this.service.findUserGid (uid);
        SecUser user = this.service.selectByPrimaryKey (uid);
        ui.put ("groups", groups);
        ui.put ("gids", gids);
        ui.put ("user", user);
        return PRE + "groups";
    }

    @RequestMapping("/group")
    @ResponseBody
    public RespMSG grantGroup(Integer uid, Integer gids[]) {
        int res = 0;
        res = this.service.updateUserGroups (uid, gids);
        RespMSG msg = new RespMSG (RespCode.SUCCESS);
        msg.setData (res);
        return msg;
    }

    /**
     * 新增功能
     *
     * @param bean
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public RespMSG create(SecUser bean, HttpSession session) {
        bean.setPasswd ("123456");
        DateTime dateTime = new DateTime ();
        dateTime.plusDays (90);//90天密码过期
        bean.setPwdEndDate (dateTime.toDate ());
        bean.setUseState ("-1");
        bean.setDelState ("0");
        ComplexResult result = FluentValidator.checkAll ()
                .on (bean.getLoginName (), new NotNullValidator ("登录名"))
                .on (bean.getPasswd (), new NotNullValidator ("密码"))
                .on (bean.getNickName (), new NotNullValidator ("昵称"))
                .on (bean.getMobile (), new NotNullValidator ("手机号"))
                .on (bean.getEmail (), new EmailValidator ("邮箱"))
                .doValidate ()
                .result (ResultCollectors.toComplex ());
        if (!result.isSuccess ()) {
            RespMSG error = new RespMSG (RespCode.FAIL);
            error.setDesc (ValidationErrorToString.errorToString (result.getErrors (), "\n\r"));
            return error;
        }
        bean.setCreateTs (new Date ());
        bean.setUpdateTs (new Date ());
        bean.setCreateUid ((Integer) session.getAttribute (SecurityConstants.CURRENT_UID));
        bean.setUpdateUid ((Integer) session.getAttribute (SecurityConstants.CURRENT_UID));
        int count = service.insertSelective (bean);
        return new RespMSG (RespCode.SUCCESS);
    }

    /**
     * 更新功能
     *
     * @param id
     * @param bean
     * @return
     */
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public RespMSG update(@PathVariable("id") int id, SecUser bean, HttpSession session) {
        //TODO 验证数据，验证完成，设定主键为id
        ComplexResult result = FluentValidator.checkAll ()
                .on (bean.getNickName (), new NotNullValidator ("昵称"))
                .on (bean.getMobile (), new NotNullValidator ("手机号"))
                .on (bean.getEmail (), new EmailValidator ("邮箱"))
                .doValidate ()
                .result (ResultCollectors.toComplex ());
        if (!result.isSuccess ()) {
            RespMSG error = new RespMSG (RespCode.FAIL);
            error.setDesc (ValidationErrorToString.errorToString (result.getErrors (), "\n\r"));
            return error;
        }
        if (id < 5) {
            RespMSG error = new RespMSG (RespCode.FAIL);
            error.setDesc ("内置数据无法操作");
            return error;
        }
        bean.setUpdateTs (new Date ());
        bean.setUpdateUid ((Integer) session.getAttribute (SecurityConstants.CURRENT_UID));
        int count = service.updateByPrimaryKeySelective (bean);
        return new RespMSG (RespCode.SUCCESS);
    }

    /**
     * 更新功能
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/initPwd/{id}", method = RequestMethod.POST)
    @ResponseBody
    public RespMSG initPwd(@PathVariable("id") int id, HttpSession session) {
        SecUser bean = new SecUser ();
        bean.setUid (id);
        bean.setPasswd ("123456");
        DateTime dateTime = new DateTime ();
        dateTime.plusDays (1);//重置密码之后1天密码过期
        bean.setPwdEndDate (dateTime.toDate ());
        bean.setUpdateTs (new Date ());
        bean.setUpdateUid ((Integer) session.getAttribute (SecurityConstants.CURRENT_UID));
        int count = service.updateByPrimaryKeySelective (bean);
        return new RespMSG (RespCode.SUCCESS);
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/delete/{ids}", method = RequestMethod.POST)
    @ResponseBody
    public RespMSG delete(@PathVariable("ids") String ids) {
        if (ids.contains ("-1-") || ids.endsWith ("-1") || ids.startsWith ("1-") || ids.equals ("1")) {
            RespMSG error = new RespMSG (RespCode.FAIL);
            error.setDesc ("内置数据无法操作");
            return error;
        }else{
            int count = service.deleteByPrimaryKeys (ids);
            if(count >0){
                return new RespMSG (RespCode.SUCCESS);
            }else{
                return new RespMSG (RespCode.FAIL);
            }
        }


    }

    /**
     * 删除
     *
     * @return
     */
    @RequestMapping(value = "/check")
    @ResponseBody
    public boolean check(String loginName) {
        SecUserExample sue = new SecUserExample ();
        sue.createCriteria ().andLoginNameEqualTo (loginName);
        int count = this.service.countByExample (sue);
        if (count > 0) {
            return false;
        } else {
            return true;
        }
    }


    @RequestMapping("/list")
    @ResponseBody
    public Object list(
            @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
            @RequestParam(required = false, defaultValue = "", value = "search") String search,
            @RequestParam(required = false, value = "sort") String sort,
            @RequestParam(required = false, value = "order") String order) {
        SecUserExample beanExample = new SecUserExample ();
        if (!StringUtils.isBlank (sort) && !StringUtils.isBlank (order)) {
            beanExample.setOrderByClause (sort + " " + order);
        }
        //TODO 模糊查询定义
        List<SecUser> rows = service.selectByExampleForOffsetPage (beanExample, offset, limit);
        long total = service.countByExample (beanExample);
        Map<String, Object> result = new HashMap<> ();
        result.put ("rows", rows);
        result.put ("total", total);
        return result;
    }
}
